package top.fullj.io;

import com.google.common.base.Preconditions;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * @author bruce.wu
 * @since 2019/11/21 15:43
 */
public abstract class FileStreamCompat {

    private static final String PATH_PREFIX = "classpath:";

    public static InputStream getInputStream(String path) throws FileNotFoundException {
        Preconditions.checkNotNull(path);
        if (!path.startsWith(PATH_PREFIX)) {
            return new FileInputStream(path);
        }
        return getClassPathResourceStream(path.substring(PATH_PREFIX.length()));
    }

    private static InputStream getClassPathResourceStream(String path) throws FileNotFoundException {
        String pathToUse = path.replace("\\", "/");
        if (pathToUse.startsWith("/")) {
            pathToUse = pathToUse.substring(1);
        }
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream is = classLoader == null
                ? ClassLoader.getSystemResourceAsStream(pathToUse)
                : classLoader.getResourceAsStream(pathToUse);
        if (is == null) {
            throw new FileNotFoundException("classpath resource[" + path + "]");
        }
        return is;
    }

}
